package com.rc.saas.tenant.service.enterprise;

import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.common.utils.MD5Utils;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseMemberMapper;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseSubmemberApplyMapper;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseSubmemberMapper;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseSubmemberRecordMapper;
import com.rc.saas.tenant.model.enterprise.*;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.rc.RcOperatorAccountRecord;
import com.rc.saas.tenant.model.recharge.RechargeOrder;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.enterprise.EnterpriseMemberSearch;
import com.rc.saas.tenant.service.finance.RcOperatorAccountRecordService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.recharge.RechargeOrderService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.vo.enterprise.EnterpriseMemberPrintVo;
import com.rc.saas.tenant.vo.enterprise.EnterpriseMemberResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

/**
 * @author frog
 * @date 2019/9/25
 */
@Service
public class EnterpriseMemberServiceImpl implements EnterpriseMemberService {
    private static Logger logger = LogManager.getLogger(EnterpriseMemberService.class);

    @Autowired
    private EnterpriseMemberMapper enterpriseMemberMapper;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private EnterpriseSubmemberMapper enterpriseSubmemberMapper;

    @Autowired
    private EnterpriseSubmemberRecordMapper enterpriseSubmemberRecordMapper;

    @Autowired
    private EnterpriseSubmemberShareService enterpriseSubmemberShareService;

    @Autowired
    private EnterpriseSubmemberApplyMapper enterpriseSubmemberApplyMapper;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private RcEnterpriseGainRecordService enterpriseGainRecordService;

    @Autowired
    private RcEnterpriseLevelSettingService levelSettingService;

    @Autowired
    private RcEnterpriseGainSettingService gainSettingService;

    @Autowired
    private RcEnterpriseGainGradeSettingService gradeSettingService;

    @Autowired
    private RcEnterpriseGainRecordService gainRecordService;

    @Autowired
    private RcEnterpriseGainGradeRecordService gradeRecordService;

    @Autowired
    private RechargeOrderService rechargeOrderService;

    @Autowired
    private RcOperatorAccountRecordService operatorAccountRecordService;


    @Override
    public EnterpriseMemberMapper getMapper() {
        return enterpriseMemberMapper;
    }

    //@Override
    //public EnterpriseMember selectByLoginName(String loginName) {
    //EnterpriseMemberExample example = new EnterpriseMemberExample();
    //example.createCriteria().andLoginNameEqualTo(loginName);
    //List<TenantOperator> list = enterpriseMemberMapper.selectByExample(example);
    //if (!CollectionUtils.isEmpty(list)) {
    //    return list.get(0);
    //}
    //return null;
    //}


    @Override
    public Long insertReturnId(EnterpriseMember enterpriseMember) {
        return enterpriseMemberMapper.insertReturnId(enterpriseMember);
    }

    @Override
    public TResponse resetPassword(TenantUser tenantUser, String password) {
        String saltPassword = MD5Utils.encrypt(tenantUser.getLoginName(), password);
        logger.info("重置密码:{},:{}", tenantUser.getLoginName(), password);
        //保存登录帐户资料
        TenantUser newTenantUser = new TenantUser();
        newTenantUser.setTenantUserId(tenantUser.getTenantUserId());
        newTenantUser.setPassword(saltPassword);
        tenantUserService.updateByPrimaryKeySelective(newTenantUser);

        return TResponse.SUCCESS(password);
    }

    @Override
    public TResponse insertOneEnterpriseSubmember(String mobile, Long enterpriseId, TenantUser user) {

        MemberInfo memberInfo = memberInfoService.selectMemberByMobile(user.getTenantCode(), mobile);
        if (memberInfo == null) {
            return TResponse.FAIL("此手机号不为会员");
        } else if ("1".equals(memberInfo.getMemberType()) || "2".equals(memberInfo.getMemberType())) {
            return TResponse.FAIL("该账号已经是企业会员");
        }
        EnterpriseSubmemberApplyExample example = new EnterpriseSubmemberApplyExample();
        example.createCriteria().andSubMemberIdEqualTo(memberInfo.getMemberId()).andStatusEqualTo("0");
        List<EnterpriseSubmemberApply> enterpriseSubmemberApplies = enterpriseSubmemberApplyMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(enterpriseSubmemberApplies)) {
            return TResponse.FAIL("该会员已经存在申请");
        }

        insertEnterpriseSubmember(enterpriseId, memberInfo);
        return TResponse.SUCCESS();
    }

    private void insertEnterpriseSubmember(Long enterpriseId, MemberInfo memberInfo) {
        EnterpriseMember enterpriseMember = enterpriseMemberMapper.selectByPrimaryKey(enterpriseId);

        EnterpriseSubmember oldEnterpriseSubmember = enterpriseSubmemberMapper.selectByPrimaryKey(memberInfo.getMemberId());
        if (oldEnterpriseSubmember != null) {
            oldEnterpriseSubmember.setBelongEnterpriseId(enterpriseId);
            oldEnterpriseSubmember.setStatus("0");
            enterpriseSubmemberMapper.updateByPrimaryKeySelective(oldEnterpriseSubmember);
        } else {
            EnterpriseSubmember enterpriseSubmember = new EnterpriseSubmember();
            enterpriseSubmember.setMemberId(memberInfo.getMemberId());
            enterpriseSubmember.setTenantCode(memberInfo.getTenantCode());
            enterpriseSubmember.setBelongEnterpriseId(enterpriseId);
            enterpriseSubmember.setStatus("0");
            enterpriseSubmemberMapper.insertSelective(enterpriseSubmember);
        }


        EnterpriseSubmemberRecord enterpriseSubmemberRecord = new EnterpriseSubmemberRecord();
        enterpriseSubmemberRecord.setTenantCode(memberInfo.getTenantCode());
        enterpriseSubmemberRecord.setSubMemberId(memberInfo.getMemberId());
        enterpriseSubmemberRecord.setEnterpriseMemberId(enterpriseMember.getMemberId());
        enterpriseSubmemberRecord.setEnterpriseId(enterpriseId);
        //记录类型 0 子会员申请成功 1子会员注销成功 2子会员冻结成功 3运营商分配 4运营商注销  默认0
        enterpriseSubmemberRecord.setRecordType("3");
        enterpriseSubmemberRecordMapper.insertSelective(enterpriseSubmemberRecord);

        memberInfo.setEnterpriseMemberId(enterpriseMember.getMemberId());
        memberInfo.setBelongEnterpriseId(enterpriseId);
        memberInfo.setMemberType("2");
        memberInfoService.updateByPrimaryKeySelective(memberInfo);

        EnterpriseSubmemberApply enterpriseSubmemberApply = new EnterpriseSubmemberApply();
        enterpriseSubmemberApply.setTenantCode(memberInfo.getTenantCode());
        enterpriseSubmemberApply.setEnterpriseMemberId(enterpriseMember.getMemberId());
        enterpriseSubmemberApply.setEnterpriseMobile(memberInfo.getMobile());
        enterpriseSubmemberApply.setSubMemberId(memberInfo.getMemberId());
        enterpriseSubmemberApply.setSubmemberMobile(memberInfo.getMobile());
        enterpriseSubmemberApply.setSubmemberNickname(memberInfo.getNickname2());
        enterpriseSubmemberApply.setApplyType("0");
        enterpriseSubmemberApply.setApplySource("1");
        enterpriseSubmemberApply.setStatus("1");

        enterpriseSubmemberApplyMapper.insertSelective(enterpriseSubmemberApply);
    }

    @Override
    public TResponse insertBatchEnterpriseSubmember(String batchMobile, Long enterpriseId, TenantUser user) {
        int memberCount = 0;
        StringBuilder mobileError = new StringBuilder();
        StringBuilder alreadyMember = new StringBuilder();
        String[] mobileList = batchMobile.split(",");
        for (String mobile : mobileList) {
            MemberInfo memberInfo = memberInfoService.selectMemberByMobile(user.getTenantCode(), mobile);
            List<EnterpriseSubmemberApply> enterpriseSubmemberApplies = new ArrayList<>();
            if (memberInfo != null) {
                EnterpriseSubmemberApplyExample example = new EnterpriseSubmemberApplyExample();
                example.createCriteria().andSubMemberIdEqualTo(memberInfo.getMemberId()).andStatusEqualTo("0");
                enterpriseSubmemberApplies = enterpriseSubmemberApplyMapper.selectByExample(example);
            }

            if (memberInfo == null) {
                mobileError.append(mobile).append(",");
            } else if (!"0".equals(memberInfo.getMemberType())) {
                alreadyMember.append(mobile).append(",");
            } else if (!CollectionUtils.isEmpty(enterpriseSubmemberApplies)) {
                alreadyMember.append(mobile).append(",");
            } else {
                insertEnterpriseSubmember(enterpriseId, memberInfo);
                memberCount++;
            }
        }
        if (StringUtil.isNotBlank(mobileError.toString()) && StringUtil.isNotBlank(alreadyMember.toString())) {
            return TResponse.SUCCESS_CODE_MESSAGE(201, String.format("成功添加子会员%d个子会员,其中添加错误的手机号为%s已经是特殊会员或存在申请的手机号为的手机号为%s",
                    memberCount, mobileError.toString(), alreadyMember.toString()));
        } else if (StringUtil.isNotBlank(alreadyMember.toString()) && StringUtil.isBlank(mobileError.toString())) {
            return TResponse.SUCCESS_CODE_MESSAGE(201, String.format("成功添加子会员%d个子会员,已经是特殊会员或存在申请的手机号为%s",
                    memberCount, alreadyMember.toString()));
        } else if (StringUtil.isNotBlank(mobileError.toString()) && StringUtil.isBlank(alreadyMember.toString())) {
            return TResponse.SUCCESS_CODE_MESSAGE(201, String.format("成功添加子会员%d个子会员,其中添加错误的手机号为%s",
                    memberCount, mobileError.toString()));
        } else {
            return TResponse.SUCCESS(String.format("成功添加子会员%d个子会员", memberCount));
        }
    }

    @Override
    public EnterpriseMember selectEnterpriseMemberByMigrateId(String tenantCode, Long migrateId) {
        EnterpriseMemberExample example = new EnterpriseMemberExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode).andMigrateIdEqualTo(migrateId);
        List<EnterpriseMember> list = enterpriseMemberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public EnterpriseMember selectMemberByMobile(String tenantCode, String enterpriseMobile) {
        EnterpriseMemberExample example = new EnterpriseMemberExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode).andEnterpriseMobileEqualTo(enterpriseMobile);
        List<EnterpriseMember> enterpriseMembers = enterpriseMemberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(enterpriseMembers)) {
            return enterpriseMembers.get(0);
        }
        return null;
    }

    @Override
    public TResponse saveEnterpriseShare(EnterpriseSubmemberShare enterpriseSubmemberShare) {

        EnterpriseMember enterpriseMember = enterpriseMemberMapper.selectByPrimaryKey(enterpriseSubmemberShare.getEnterpriseId());

        EnterpriseSubmember enterprise = new EnterpriseSubmember();
        enterprise.setMemberId(enterpriseMember.getMemberId());
        enterprise.setTenantCode(enterpriseMember.getTenantCode());

        List<EnterpriseSubmember> enterpriseSubmemberList = selectAllSubmemberByEnterpriseId(enterpriseSubmemberShare.getEnterpriseId());
        enterpriseSubmemberList.add(enterprise);
        for (EnterpriseSubmember enterpriseSubmember : enterpriseSubmemberList) {
            EnterpriseSubmemberShare submemberShareExist = enterpriseSubmemberShareService.selectByMemberId(enterpriseSubmember.getMemberId());
            insertEnterpriseShare(enterpriseSubmemberShare, submemberShareExist, enterpriseSubmember, enterpriseMember, enterpriseMember.getEnterpriseId());
        }
        return TResponse.SUCCESS();
    }

    @Override
    public List<EnterpriseSubmember> selectAllSubmemberByEnterpriseId(Long enterpriseId) {
        EnterpriseSubmemberExample example = new EnterpriseSubmemberExample();
        example.createCriteria().andBelongEnterpriseIdEqualTo(enterpriseId);
        List<EnterpriseSubmember> enterpriseSubmemberList = enterpriseSubmemberMapper.selectByExample(example);
        return enterpriseSubmemberList;
    }

    @Override
    public TResponse saveSubmemberShare(EnterpriseSubmemberShare enterpriseSubmemberShare) {

        EnterpriseSubmemberShare submemberShareExist = enterpriseSubmemberShareService.selectByMemberId(enterpriseSubmemberShare.getMemberId());

        EnterpriseSubmember enterpriseSubmember = enterpriseSubmemberMapper.selectByPrimaryKey(enterpriseSubmemberShare.getMemberId());

        EnterpriseMember enterpriseMember = enterpriseMemberMapper.selectByPrimaryKey(enterpriseSubmember.getBelongEnterpriseId());

        insertEnterpriseShare(enterpriseSubmemberShare, submemberShareExist, enterpriseSubmember, enterpriseMember, enterpriseSubmember.getBelongEnterpriseId());
        return TResponse.SUCCESS();
    }

    @Override
    public EnterpriseMember selectMemberByMemberId(Long memberId) {
        EnterpriseMemberExample example = new EnterpriseMemberExample();
        example.createCriteria().andMemberIdEqualTo(memberId);
        List<EnterpriseMember> enterpriseMembers = enterpriseMemberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(enterpriseMembers)) {
            return enterpriseMembers.get(0);
        }
        return null;
    }

    @Override
    public List<EnterpriseMemberPrintVo> exportEnterpriseMember(EnterpriseMemberSearch enterpriseMemberSearch) {
        return enterpriseMemberMapper.exportEnterpriseMember(enterpriseMemberSearch);
    }


    private void insertEnterpriseShare(EnterpriseSubmemberShare enterpriseSubmemberShare, EnterpriseSubmemberShare submemberShareExist, EnterpriseSubmember enterpriseSubmember, EnterpriseMember enterpriseMember, Long belongEnterpriseId) {
        if (submemberShareExist != null) {
            submemberShareExist.setStatus(enterpriseSubmemberShare.getStatus());
            submemberShareExist.setBeginTime(enterpriseSubmemberShare.getBeginTime());
            submemberShareExist.setEndTime(enterpriseSubmemberShare.getEndTime());
            submemberShareExist.setShareType(enterpriseSubmemberShare.getShareType());
            submemberShareExist.setFixedPower(enterpriseSubmemberShare.getFixedPower());
            submemberShareExist.setFixedAccount(enterpriseSubmemberShare.getFixedAccount());
            submemberShareExist.setShareAccount(new BigDecimal(0));
            submemberShareExist.setSharePower(new BigDecimal(0));
            enterpriseSubmemberShareService.updateByPrimaryKeySelective(submemberShareExist);
        } else {
            EnterpriseSubmemberShare submemberShareNew = new EnterpriseSubmemberShare();
            submemberShareNew.setStatus(enterpriseSubmemberShare.getStatus());
            submemberShareNew.setBeginTime(enterpriseSubmemberShare.getBeginTime());
            submemberShareNew.setEndTime(enterpriseSubmemberShare.getEndTime());
            submemberShareNew.setShareType(enterpriseSubmemberShare.getShareType());
            submemberShareNew.setFixedPower(enterpriseSubmemberShare.getFixedPower());
            submemberShareNew.setFixedAccount(enterpriseSubmemberShare.getFixedAccount());

            submemberShareNew.setTenantCode(enterpriseSubmember.getTenantCode());
            submemberShareNew.setEnterpriseId(belongEnterpriseId);
            submemberShareNew.setEnterpriseMemberId(enterpriseMember.getMemberId());
            submemberShareNew.setMemberId(enterpriseSubmember.getMemberId());
            submemberShareNew.setSharePower(new BigDecimal(0));
            submemberShareNew.setShareAccount(new BigDecimal(0));
            enterpriseSubmemberShareService.insertSelective(submemberShareNew);
        }
    }

    @Override
    public PageInfo<EnterpriseMemberResult> listPageEnterpriseMember(EnterpriseMemberSearch search) {
        PageHelper.startPage(search.getOffset(), search.getLimit());
        List<EnterpriseMemberResult> enterpriseMemberList = enterpriseMemberMapper.searchByCondition(search);


        enterpriseMemberList.forEach(enterpriseMemberResult ->{
            RcEnterpriseGainRecordExample example = new RcEnterpriseGainRecordExample();
            example.createCriteria().andMemberIdEqualTo(enterpriseMemberResult.getMemberId());
            RcEnterpriseGainRecord enterpriseGainRecord = enterpriseGainRecordService.selectByExample(example).stream().findFirst().orElseGet(() -> null);
            if (enterpriseGainRecord != null) {
                enterpriseMemberResult.setEnterpriseLevel(enterpriseGainRecord.getEnterpriseLevel());
            }
        });

        return new PageInfo<EnterpriseMemberResult>(enterpriseMemberList);
    }

    @Override
    public TResponse updateStatus(Long memberId) {
        EnterpriseMember enterpriseMember = enterpriseMemberMapper.selectMemberByMemberId(memberId);
        MemberInfo memberInfo=memberInfoService.selectByPrimaryKey(memberId);
        //主会员对应的子会员
        EnterpriseSubmemberExample enterpriseSubmemberExample=new EnterpriseSubmemberExample();
        enterpriseSubmemberExample.createCriteria().andBelongEnterpriseIdEqualTo(enterpriseMember.getEnterpriseId());
        List<EnterpriseSubmember> enterpriseSubmembers=enterpriseSubmemberMapper.selectByExample(enterpriseSubmemberExample);
        if ("1".equals(memberInfo.getStatus()) && "1".equals(enterpriseMember.getStatus())) {
            //如果该会员被冻结，企业会员及子会员无法解冻
            return TResponse.FAIL("该会员被冻结，企业会员及子会员无法解冻");
        } else if ("0".equals(memberInfo.getStatus()) && "1".equals(enterpriseMember.getStatus())) {
            enterpriseMember.setStatus("0");
        } else {
            enterpriseMember.setStatus("1");
        }
        if (!CollectionUtils.isEmpty(enterpriseSubmembers)){
            //如果冻结/解冻主会员，该主会员的子会员也要冻结/解冻
            for (EnterpriseSubmember enterpriseSubmember:enterpriseSubmembers) {
//                enterpriseSubmemberService.updateStatus(enterpriseMembe1.getMemberId());
                if ("0".equals(enterpriseSubmember.getStatus())) {
                    enterpriseSubmember.setStatus("2");
                } else if ("2".equals(enterpriseSubmember.getStatus())) {
                    enterpriseSubmember.setStatus("0");
                }
                enterpriseSubmemberMapper.updateByPrimaryKeySelective(enterpriseSubmember);
            }
        }
        enterpriseMemberMapper.updateByPrimaryKeySelective(enterpriseMember);
        return TResponse.SUCCESS();
    }

    @Override
    public List<EnterpriseMember> selectEnterpriseMembers(String tenantCode) {
        EnterpriseMemberExample example = new EnterpriseMemberExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode);
        return enterpriseMemberMapper.selectByExample(example);
    }

    @Override
    public void updateEnterpriseForRecharge(Long enterpriseId, BigDecimal money) {
        EnterpriseMember enterprise = enterpriseMemberMapper.selectByPrimaryKey(enterpriseId);

        //累计充值金额
        BigDecimal totalMoney = enterprise.getAllRechargeEnterpriseAccount().add(money);

        RechargeOrder rechargeOrder = new RechargeOrder();
        rechargeOrder.setTenantCode(enterprise.getTenantCode());

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSSSSS");
        String outTradeNo = MD5Utils.encrypt(dateFormat.format(date) + enterpriseId + money.toString()).toUpperCase();
        rechargeOrder.setOutTradeNo(outTradeNo);
        rechargeOrder.setAmount(money);
        rechargeOrder.setFactAmount(money);
        rechargeOrder.setGiveAmount(BigDecimal.ZERO);
        rechargeOrder.setRechargeType("3");
        rechargeOrder.setIsRefund("0");
        rechargeOrder.setPaymentType("3");
        rechargeOrder.setFinishTime(date);
        rechargeOrder.setStatus("1");
        rechargeOrder.setUserType("1");
        rechargeOrder.setEnterpriseId(enterpriseId);
        rechargeOrderService.insertSelective(rechargeOrder);

        RcOperatorAccountRecord operatorAccountRecord = new RcOperatorAccountRecord();
        operatorAccountRecord.setTenantCode("MA4T4JPE8");
        operatorAccountRecord.setRecordType("0");
        operatorAccountRecord.setExplains("充值");
        operatorAccountRecord.setOrderNum(outTradeNo);
        operatorAccountRecord.setRecordSource("0");
        operatorAccountRecord.setAmount(money);
        operatorAccountRecord.setEntryId(0l);
        operatorAccountRecord.setEntryName("平台");
        operatorAccountRecord.setEntryType("0");
        operatorAccountRecord.setOutId(enterpriseId);
        operatorAccountRecord.setOutName(enterprise.getEnterpriseName());
        operatorAccountRecord.setOutType("0");
        operatorAccountRecord.setOutAccount(enterprise.getEnterpriseAccount().add(money));
        operatorAccountRecord.setStatus("0");
        operatorAccountRecord.setRemark("平台给企业充值");
        operatorAccountRecord.setCreatedTime(new Date());
        operatorAccountRecordService.insertSelective(operatorAccountRecord);


        RcEnterpriseLevelSetting enterpriseLevelSetting = levelSettingService.selectLevelBetweenInterval(money);
        //升级
        if (enterpriseLevelSetting != null && !enterpriseLevelSetting.getEnterpriseLevel().equals(enterprise.getEnterpriseLevel())) {
            List<RcEnterpriseGainSetting> gainList = gainSettingService.listGainSettingByLevel(enterpriseLevelSetting.getEnterpriseLevel());
            gainRecordService.deleteGainRecordByEnterpriseId(enterpriseId);
            gradeRecordService.deleteGradeRecordByEnterpriseId(enterpriseId);

            for (RcEnterpriseGainSetting gain : gainList) {
                //新增权益记录
                RcEnterpriseGainRecord gainRecord = new RcEnterpriseGainRecord();
                gainRecord.setEnterpriseGainId(gain.getEnterpriseGainId());
                gainRecord.setEnterpriseLevel(enterpriseLevelSetting.getEnterpriseLevel());
                gainRecord.setEnterpriseId(enterpriseId);
                gainRecord.setMemberId(enterprise.getMemberId());
                gainRecord.setGainName(gain.getGainName());
                gainRecord.setGainType(gain.getGainType());
                gainRecord.setGainLogo(gain.getGainLogo());
                gainRecord.setSort(gain.getSort());
                gainRecord.setGainExplain(gain.getGainExplain());
                gainRecordService.insertReturnId(gainRecord);

                //新增权益档位记录
                List<RcEnterpriseGainGradeSetting> gainGradeList = gradeSettingService.listGradeByGain(gain.getEnterpriseGainId());
                for (RcEnterpriseGainGradeSetting gainGradeSetting: gainGradeList) {
                    RcEnterpriseGainGradeRecord gradeRecord = new RcEnterpriseGainGradeRecord();
                    gradeRecord.setEnterpriseGainRecordId(gainRecord.getEnterpriseGainRecordId());
                    gradeRecord.setEnterpriseGainId(gain.getEnterpriseGainId());
                    gradeRecord.setEnterpriseId(enterprise.getEnterpriseId());
                    gradeRecord.setMemberId(enterprise.getMemberId());
                    gradeRecord.setRechargeAmount(gainGradeSetting.getRechargeAmount());
                    gradeRecord.setDiscountAmount(gainGradeSetting.getDiscountAmount());
                    gradeRecord.setGainLogo(gainGradeSetting.getGainLogo());
                    gradeRecordService.insertSelective(gradeRecord);
                }
            }
        }

        enterprise.setAllRechargeEnterpriseAccount(totalMoney);
        enterprise.setEnterpriseAccount(enterprise.getEnterpriseAccount().add(money));
        if(enterpriseLevelSetting != null) {
            if (!enterpriseLevelSetting.getEnterpriseLevel().equals(enterprise.getEnterpriseLevel())) {
//                enterprise.setCreditAmount(enterpriseLevelSetting.getCreditAmountTarget());
//                enterprise.setRemainCreditAmount(enterpriseLevelSetting.getCreditAmountTarget());
                enterprise.setEnterpriseLevel(enterpriseLevelSetting.getEnterpriseLevel());
            }
        }
        enterpriseMemberMapper.updateByPrimaryKeySelective(enterprise);
    }

    @Override
    public void updateEnterpriseForCredit(Long enterpriseId, BigDecimal creditAmount) {
        EnterpriseMember enterprise = enterpriseMemberMapper.selectByPrimaryKey(enterpriseId);
        enterprise.setCreditAmount(creditAmount);
        enterprise.setRemainCreditAmount(creditAmount);
        enterprise.setLastUpdatedTime(new Date());
        enterpriseMemberMapper.updateByPrimaryKeySelective(enterprise);

    }
}